package com.guowen.myaccount;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.guowen.myaccount.db.DBManager;
import com.guowen.myaccount.frag_statistics.InStatisticsFragment;
import com.guowen.myaccount.frag_statistics.OutStatisticsFragment;

import java.util.Calendar;

public class StatisticsActivity extends AppCompatActivity implements View.OnClickListener{

    private ImageView backIv, leftIv, rightIv;
    private TextView timeMonthTv, timeYearTv;
    private TextView timeHeadTv, timeFootTv;
    private TextView staTv1, staTv2, staTv3;
    public static int YEAR, MONTH, DAY;
    public static int TIME = 0; // 默认月份分析，值为0，年份分析值为1
    public MyFragmentAdpater adpater;
    public ViewPager2 viewPagerFragments;
    InStatisticsFragment inStatisticsFragment;
    OutStatisticsFragment outStatisticsFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistics);

        initView();
        initTime();
        initData();

        TabLayout tabLayoutHeader= findViewById(R.id.activity_statistics_tab);
        TabLayoutMediator tabLayoutMediator=new TabLayoutMediator(tabLayoutHeader, viewPagerFragments, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                switch (position) {
                    case 0:
                        tab.setText("支出");
                        break;
                    case 1:
                        tab.setText("收入");
                        break;
                }
            }
        });
        tabLayoutMediator.attach();

    }

    @SuppressLint("NotifyDataSetChanged")
    private void initData() {
        if (TIME == 0){
            int endDays = getDays(YEAR,MONTH);
            timeHeadTv.setText(YEAR+"-"+MONTH+"-01");
            timeFootTv.setText(YEAR+"-"+MONTH+"-"+endDays);
            float outcome = DBManager.getSumMoneyOneMonth(YEAR, MONTH, 0);
            float income = DBManager.getSumMoneyOneMonth(YEAR, MONTH, 1);
            String tv1 = "支出："+outcome+"，收入："+income+"，结余：" +(income-outcome);
            staTv1.setText(tv1);
            int num_outrecord = DBManager.getAccountListOneMonthFromAccounttbByKind(YEAR,MONTH,0).size();
            int num_inrecord = DBManager.getAccountListOneMonthFromAccounttbByKind(YEAR,MONTH,1).size();
            String tv2 = "";
            if (num_outrecord != 0){
                tv2 = "支出平均每日："+(outcome/endDays)+"，平均每笔："+(outcome/num_outrecord);
            }else {
                tv2 = "支出平均每日：0.0，平均每笔：0.0";
            }
            staTv2.setText(tv2);
            String tv3 = "";
            if (num_inrecord != 0){
                tv3 = "收入平均每日："+(income/endDays)+"，平均每笔："+(income/num_inrecord);
            }else {
                tv3 = "收入平均每日：0.0，平均每笔：0.0";
            }
            staTv3.setText(tv3);

        }else {
            int allDays = 0;
            if (isLeap(YEAR))
                allDays = 366;
            else allDays = 365;
            timeHeadTv.setText(YEAR+"-01-01");
            timeFootTv.setText(YEAR+"-12-31");
            float outcome = DBManager.getSumMoneyOneYear(YEAR, 0);
            float income = DBManager.getSumMoneyOneYear(YEAR, 1);
            String tv1 = "支出："+outcome+"，收入："+income+"，结余：" +(income-outcome);
            staTv1.setText(tv1);
            int num_outrecord = DBManager.getAccountListOneYearFromAccounttbByKind(YEAR,0).size();
            int num_inrecord = DBManager.getAccountListOneYearFromAccounttbByKind(YEAR,1).size();
            String tv2 = "";
            if (num_outrecord != 0){
                tv2 = "支出平均每日："+(outcome/allDays)+"，平均每笔："+(outcome/num_outrecord);
            }else {
                tv2 = "支出平均每日：0.0，平均每笔：0.0";
            }
            staTv2.setText(tv2);
            String tv3 = "";
            if (num_inrecord != 0){
                tv3 = "收入平均每日："+(income/allDays)+"，平均每笔："+(income/num_inrecord);
            }else {
                tv3 = "收入平均每日：0.0，平均每笔：0.0";
            }
            staTv3.setText(tv3);
        }

        outStatisticsFragment = new OutStatisticsFragment();
        inStatisticsFragment = new InStatisticsFragment();

        adpater = new MyFragmentAdpater(this);
        adpater.notifyDataSetChanged();
        viewPagerFragments.setAdapter(adpater);
    }

    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        YEAR = calendar.get(Calendar.YEAR);
        MONTH = calendar.get(Calendar.MONTH) + 1;
        DAY = calendar.get(Calendar.DAY_OF_MONTH);
    }

    private void initView() {
        backIv = findViewById(R.id.activity_statistics_back);
        timeMonthTv = findViewById(R.id.activity_statistics_tv_month);
        timeYearTv = findViewById(R.id.activity_statistics_tv_year);
        timeHeadTv = findViewById(R.id.activity_statistics_tv_head);
        timeFootTv = findViewById(R.id.activity_statistics_tv_foot);
        staTv1 = findViewById(R.id.activity_statistics_tv1);
        staTv2 = findViewById(R.id.activity_statistics_tv2);
        staTv3 = findViewById(R.id.activity_statistics_tv3);
        leftIv = findViewById(R.id.activity_statistics_left);
        rightIv = findViewById(R.id.activity_statistics_right);
        viewPagerFragments = findViewById(R.id.activity_statistics_vp2);

        backIv.setOnClickListener(this);
        timeMonthTv.setOnClickListener(this);
        timeYearTv.setOnClickListener(this);
        leftIv.setOnClickListener(this);
        rightIv.setOnClickListener(this);
        timeHeadTv.setOnClickListener(this);
        timeFootTv.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_statistics_back:
                finish();
                break;
            case R.id.activity_statistics_tv_month:
                TIME = 0;
                timeMonthTv.setTextColor(Color.rgb(43,153,242));
                timeYearTv.setTextColor(Color.rgb(243,243,243));
                initData();
                break;
            case R.id.activity_statistics_tv_year:
                timeMonthTv.setTextColor(Color.rgb(243,243,243));
                timeYearTv.setTextColor(Color.rgb(43,153,242));
                TIME = 1;
                initData();
                break;
            case R.id.activity_statistics_left:
                if (TIME == 0){
                    MONTH -= 1;
                    if (MONTH <= 0){
                        MONTH = 12;
                        YEAR -= 1;
                    }
                }else {
                    YEAR -= 1;
                }
                initData();
                break;
            case R.id.activity_statistics_right:
                if (TIME == 0){
                    MONTH += 1;
                    if (MONTH >= 13){
                        MONTH = 1;
                        YEAR += 1;
                    }
                }else {
                    YEAR += 1;
                }
                initData();
                break;
            case R.id.activity_statistics_tv_head:
            case R.id.activity_statistics_tv_foot:
                new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year1, int month1, int dayOfMonth) {
                        MONTH = month1+1;
                        YEAR = year1;
                        initData();
                    }
                },YEAR,MONTH-1,DAY).show();
                break;
        }
    }

    //判断闰年
    boolean isLeap(int year)
    {
        if (((year % 100 == 0) && year % 400 == 0) || ((year % 100 != 0) && year % 4 == 0))
            return true;
        else
            return false;
    }

    //返回当月天数
    int getDays(int year, int month)
    {
        int days;
        int FebDay = 28;
        if (isLeap(year))
            FebDay = 29;
        switch (month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            case 2:
                days = FebDay;
                break;
            default:
                days = 0;
                break;
        }
        return days;
    }

    private class MyFragmentAdpater extends FragmentStateAdapter {


        public MyFragmentAdpater(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            switch(position)
            {
                case 0:
                    return outStatisticsFragment;
                default:
                    return inStatisticsFragment;
            }
        }

        @Override
        public int getItemCount() {
            return 2;
        }
    }

}